<template>
  <div class="dis-flex-col" :style="{ height: height + 'px' }">
    <div class="flexG0 dis-flex">
      <slot name="btn"></slot>
    </div>
    <div class="flexG1">
      <div class="chart" :id="_chartID">
        <div class="abs-lt">
          <button type="button" @click="test">clear</button>
        </div>
        <div class="abs-rt" @click="ajaxData">
          {{ sfb }}{{ _subType }}{{ _chartID }}
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import { bus } from '@/main.js';
// 引入 ECharts 主模块
import { mapState, mapMutations } from 'vuex';
// import * as echarts from 'echarts';
// import { option } from './optsBar.js';

import {
  init,
  dispose,
  registerIndicator,
  getSupportedIndicators,
} from 'klinecharts';

import { option } from './optsSubKLine2.js';
let _configOpts = option;

export default {
  name: 'subChart',
  mixins: [], //混入
  components: {}, //组件
  props: {
    _chartID: {
      type: [String],
      default: function() {
        return 'chartID_0';
      },
    },
    _subType: {
      type: [String, Number, Object],
      default: function() {
        return '0';
      },
    },
    height: {
      type: [Number],
      default: function() {
        return 677;
      },
    },
    stockCode: {
      type: [String],
      validator: function(value) {
        let re = new RegExp(/^\d{4,6}\.[A-Z]{2,3}$/);
        return re.test(value);
      },
    },
  }, //集成属性
  data() {
    return {
      isDev: process.env.NODE_ENV == 'development',
      subType: 0,
      linedata: [],
      chart: null,
      sfb: null,
    };
  },
  computed: {
    ...mapState(['winSize', 'stock']),
    params_code: function() {
      let p = {
        get_type: 'range',
        prod_code: this.stockCode,
        candle_period: 6,
        // fields
        search_direction: 2,
        data_count: 300,
        start_date: this.$moment()
          .subtract(2000, 'days')
          .format('YYYY-MM-DD'),
        end_date: this.$moment().format('YYYY-MM-DD'),
      };
      return p;
    },
  },
  watch: {
    'stock.linedata': {
      deep: true,
      handler: function(nv, ov) {
        this.chart.applyNewData(nv);
      },
    },
    _subType(nv, ov) {
      console.log(this._chartID, nv, ov);
      this.chart.removeIndicator('candle_pane', ov);
    },
  },
  methods: {
    ...mapMutations([]),
    test: function() {
      // console.log('test');
      console.log(getSupportedIndicators());
    },
    init: function() {},
    clear: function() {
      console.log('clear');
      // console.log(this.chart.getSupportedIndicators());
      this.chart.removeIndicator('candle_pane', 'Custom');
    },
    ajaxData: function() {
      console.log(this._subType);
      let p = this.params_code;
      this.$api
        .testReMock(p)
        .then((res) => {
          let d = res.data;

          registerIndicator({
            name: 'Custom',
            shortName: 'Custom',
            // series: 'price',
            figures: [{ key: 'value', title: 'Custom', type: 'line' }],
            calc: (kLineDataList) => {
              return kLineDataList.map((kLineData, i, a) => {
                return {
                  value: d[i] || 0,
                  // value: kLineData.close,
                  // text: '1',
                  text: d[i] / 10,
                };
              });
            },
            draw: ({
              ctx,
              barSpace,
              visibleRange,
              indicator,
              xAxis,
              yAxis,
              kLineDataList,
            }) => {
              const { from, to } = visibleRange;
              // ctx.font = barSpace.gapBar + 'px' + ' Helvetica Neue';
              // ctx.textAlign = 'center';
              const result = indicator.result;
              for (let i = from; i < to; i++) {
                const data = result[i];
                const x = xAxis.convertToPixel(i);
                const y = yAxis.convertToPixel(data.value);
                // ctx.fillText(data.value, x, y);
              }
              return false;
            },
          });
          let a = this.chart.createIndicator(
            'Custom',
            true,
            {
              id: 'candle_pane',
            },
            () => {}
          );
          console.log(a);
        })
        .catch((err) => {
          console.error(err);
        })
        .finally((_) => {});
    },
  },
  beforeCreate: function() {},
  created: function() {},
  beforeMount: function() {},
  mounted: function() {
    this.chart = init(this._chartID, _configOpts);
    this.chart.subscribeAction('onVisibleRangeChange', (e) => {
      // console.log(e);//e===this.chart.getVisibleRange();
      // form:number,数据左端，min0
      // realFrom:number,图表左端，可负值
      // to:number,数据右端，max
      // realTo:number,图表右端，可超值
      bus.$emit('datazoom', {
        id: this._chartID,
        event: e,
      });
      this.sfb = e;
    });
    this.chart.subscribeAction('onCrosshairChange', (e) => {});

    bus.$on('datazoom', ({ id, event }) => {
      if (id == this._chartID) return;
      this.sfb = event;
      // console.log(event);
    });
  },
  beforeUpdate: function() {},
  updated: function() {},
  beforeDestroy: function() {
    bus.$off('datazoom');
  },
  destroyed: function() {},
};
</script>
<style lang="less" scoped>
.dis-flex-col {
  position: relative;
  display: flex;
  flex-direction: column;
  .flexG1 {
    flex-grow: 1;
  }
  .flexG0 {
    flex-grow: 0;
  }
}
.chart {
  height: 100%;
}
.abs-lt {
  display: none;
  position: absolute;
  left: 0;
  top: 0;
  z-index: 7;
}
.abs-rt {
  display: none;
  position: absolute;
  right: 0;
  top: 0;
  z-index: 7;
}
</style>
